<?php
/**
 * Created by PhpStorm.
 * User: chenguangpeng
 * Date: 15-9-7
 * Time: 上午11:07
 */

namespace PFT;



class Coupon {

    private $db;
    private $mid;
    private $aid;
    private $dbConf;
    public function __construct($mid, $aid, \PDO $db=null)
    {
        if (!$mid || !is_numeric($mid)) throw new \Exception('会员ID不能为空');
        if (!$aid || !is_numeric($aid)) throw new \Exception('供应商ID不能为空');
        $this->db = $db;
        if (is_null($db)) {
            include_once '/var/www/html/new/d/module/common/Db.class.php';
            $this->dbConf = include '/var/www/html/new/d/module/common/db.conf.php';// 远端服务器配置信息
            \PFT\Db::Conf($this->dbConf['localhost']);
            $this->db = \PFT\Db::Connect();
        }
        $this->mid = $mid;
        $this->aid = $aid;
    }
    public function setMid($mid)
    {
        $this->mid = $mid;
    }
    /**
     * 已领取优惠券列表
     *
     * @param int $status
     * @return array
     */
    public function lists($status=0)
    {
        $sql = <<<SQL
SELECT mc.fid, mc.aid, mc.coupon_id, mc.dstatus, mc.end_date, mc.start_date,
mc.create_time, c.coupon_name, (c. coupon_value / 100) as coupon_value,
c.pid,c.channel,c.limit_use, (c.condition/100) as `condition` FROM pft_member_coupon mc
LEFT JOIN pft_coupons c ON(mc.coupon_id=c.id)
WHERE mc.fid=? AND mc.aid=? AND mc.dstatus=?
SQL;
//        echo $sql;
//        var_dump(array($this->mid, $this->aid, $status));
        $stmt = $this->db->prepare($sql);
        $stmt->execute(array($this->mid, $this->aid, $status));
        $data = $pids = array();
        $cnt_tmp = array();
        while ($tmp = $stmt->fetch(\PDO::FETCH_ASSOC)) {
            $tmp['ticket_name'] = '通用';
            $cnt_tmp[$tmp['coupon_id']] += 1;
            $tmp['cnt'] = $cnt_tmp[$tmp['coupon_id']];
            $data[$tmp['coupon_id']] = $tmp ;
//            $data = array_merge($data[$tmp['coupon_id']], $tmp);
            if ($tmp['pid']>0)  $pids[$tmp['pid']][] = $tmp['coupon_id'];
        }
//        print_r($cnt_tmp);
//        print_r($pids);
//        print_r($data);
        //查找产品信息
        if (count($pids)) {
            $this->getPname($data, $pids);
        }
//        $data = $stmt->fetchAll(\PDO::FETCH_ASSOC);
        return $data;
    }

    public function detail($coupon_id)
    {
        $sql = "SELECT * FROM pft_coupons WHERE id=? LIMIT 1";
        $stmt = $this->db->prepare($sql);
        $stmt->execute(array($coupon_id));
        $data = $stmt->fetch(\PDO::FETCH_ASSOC);
        $data['use_enddate']   = substr($data['use_enddate'],0, 10);
        $data['use_startdate'] = substr($data['use_startdate'],0, 10);

        if ($data['effective_type']==0 || $data['effective_type']==2) {
            $data['use_enddate']   = '';
            $data['use_startdate'] = '领取当天有效';
        }

        $sql_cnt = "SELECT count(*) from pft_member_coupon WHERE coupon_id=?";
        $stmt = $this->db->prepare($sql_cnt);
        $stmt->execute(array($coupon_id));
        $data['cnt'] = $stmt->fetchColumn();
        $data['ticket_name']   = '通用';
        $data['coupon_value'] /= 100;
        $channel_str = '使用渠道不限';
        if ($data['channel']!='') {
            $channel_str = '使用渠道限';
            $tmp_channel = explode(',', $data['channel']);
            $channel_array = array_map(function($val){
                $channel_list = array('不限','微信','二级店铺','自助机', '会员卡');
                return $channel_list[$val];
            }, $tmp_channel);
            $channel_str .= implode(',', $channel_array);
        }
        $data['condition']    = '满'.($data['condition']/100).'元使用;<br/>'.$channel_str;
        if ($data['pid']>0) {
            $sql = "SELECT p_name FROM uu_products WHERE id=? LIMIT 1";
            $stmt = $this->db->prepare($sql);
            $stmt->execute(array($data['pid']));
            $data['ticket_name'] = $stmt->fetchColumn();
        }
        return $data;
    }

    /**
     * 店铺可领取优惠券列表
     *
     * @return array
     */
    public function shop_coupons()
    {
        $sql = <<<SQL
SELECT id,coupon_name, coupon_value, use_enddate, use_startdate,`condition`,
limit_use,channel,nums, pid,collect_limit, apply_did,effective_type FROM pft_coupons
WHERE apply_did=? AND `status`=0 AND effective_type<2
SQL;
        $stmt = $this->db->prepare($sql);
        $stmt->execute(array($this->aid));
        $data = $pids = $chk_cid = array();
        while($tmp = $stmt->fetch(\PDO::FETCH_ASSOC)) {
            if ($tmp['id']==106) continue;
            $tmp['get']         = 0;//标记为未领取
            $tmp['ticket_name'] = '通用';
            if ($tmp['pid']>0)  $pids[$tmp['pid']][] = $tmp['id'];
            if ($tmp['nums']!=-1) $chk_cid[] = $tmp['id'];
            if ($tmp['effective_type']==0 ) {
                $tmp['use_enddate']   = '';
                $tmp['use_startdate'] = '领取当天有效';
            }
            $data[$tmp['id']] = $tmp;
            $data[$tmp['id']]['coupon_value'] = $tmp['coupon_value'] / 100;
            $data[$tmp['id']]['condition'] = $tmp['condition'] / 100;
        }
        //如果是有限定数量的，检测是否已经被领光了
        if (count($chk_cid)) {
            $sql_chk = "SELECT COUNT(*) AS cnt,coupon_id FROM pft_member_coupon WHERE coupon_id IN(".implode(',', $chk_cid).") GROUP BY coupon_id";
            $stmt = $this->db->prepare($sql_chk);
            $stmt->execute();
            while($tmp = $stmt->fetch(\PDO::FETCH_ASSOC)) {
                if ($tmp['cnt']>=$data[$tmp['coupon_id']]['nums']) {
                    unset($data[$tmp['coupon_id']]);
                }
            }
        }
//                print_r($data);exit;

        //检测是否已经领取了
        $sql_own = "SELECT coupon_id FROM pft_member_coupon WHERE AND coupon_id IN(".implode(',', array_keys($data)).") LIMIT ".count($data);
        $stmt = $this->db->prepare($sql_own);
        $stmt->execute(array($this->mid, $this->aid));
        while($tmp2=$stmt->fetch(\PDO::FETCH_ASSOC)) {
            $data[$tmp2['coupon_id']]['get'] = $data[$tmp2['coupon_id']]['collect_limit'] == 1 ? 1 : 0;//标记为已领取
        }
//        print_r($data);exit;
        //查找产品信息
        if (count($pids)) {
            if ($_GET['test']){
                print_r($pids);
                print_r($data);
            }
            $this->getPname($data, $pids);
        }
        return array_values($data);
    }

    private function getPname(&$data, $pids)
    {
        $sql = "SELECT id,p_name FROM uu_products WHERE id IN("
            .implode(',', array_keys($pids)).")";
        $stmt = $this->db->prepare($sql);
        $stmt->execute();
        while($tmp = $stmt->fetch(\PDO::FETCH_ASSOC)) {
            foreach($pids[$tmp['id']] as $c_id) {
                if (!$data[$c_id]) continue;
                $data[$c_id]['ticket_name'] = $tmp['p_name'];
            }
        }
//        print_r($data);
        return $data;
    }

    /**
     * 查看优惠券的领取情况
     *
     * @param $coupon_id
     * @return array
     */
    public function collection_list($coupon_id)
    {
        $data = array('lists'=>array(), 'used'=>0);
        $sql_total = "SELECT nums FROM pft_coupons WHERE id=? LIMIT 1";
        $stmt = $this->db->prepare($sql_total);
        $stmt->execute(array($coupon_id));
        $data['total'] = $stmt->fetchColumn();
        $sql = <<<SQL
  SELECT m.dname,c.dstatus,c.create_time,c.ordernum,c.start_date,
  c.end_date FROM pft_member_coupon c LEFT JOIN pft_member m ON c.fid=m.id
  WHERE c.coupon_id=? AND c.aid=?
SQL;
        $stmt = $this->db->prepare($sql);
        $stmt->execute(array($coupon_id, $this->aid));

        while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
            if ($row['dstatus']==2) {
                $data['used'] += 1;
            }
            $data['lists'][] = $row;
        }
        return $data;
    }
    /**
     * 领取优惠券
     *
     * @param int $coupon_id
     * @param int $aid
     * @param int $mid
     * @return array
     */
    public function collect_coupon($coupon_id, $aid=0, $mid=0, $from_ordernum='')
    {
        $mid = $mid > 0 ? $mid : $this->mid;
        $aid = $aid > 0 ? $aid : $this->aid;
        $sql = <<<SQL
SELECT coupon_name,use_startdate,use_enddate,nums,collect_limit,effective_type,
collect_startdate,collect_enddate FROM pft_coupons WHERE id=? LIMIT 1

SQL;
        $stmt = $this->db->prepare($sql);
        $stmt->execute(array($coupon_id));
        $coupon_data = $stmt->fetch(\PDO::FETCH_ASSOC);
        if (!$coupon_data) {
            return array('code'=>204, 'msg'=>'优惠券不存在，领取失败' );
        }
        if ($coupon_data['nums']!=-1) {
            $sql = "SELECT COUNT(id) FROM pft_member_coupon WHERE coupon_id=?";
            $stmt    = $this->db->prepare($sql);
            $stmt->execute(array($coupon_id));
            if ($stmt->fetchColumn()>=$coupon_data['nums']) {
                return array('code'=>206, 'msg'=>'抱歉，优惠券已经被领光啦');
            }
        }
        //领取时间限制
        if ( $_SERVER['REQUEST_TIME'] < strtotime($coupon_data['collect_startdate']) ) {
            return array(
                'code'=>206,
                'msg'=>'领取时间未到，该优惠券领取时间['.$coupon_data['collect_startdate'].'至'.$coupon_data['collect_enddate'].']');
        }
        if ( $_SERVER['REQUEST_TIME'] > strtotime($coupon_data['collect_enddate']) ) {
            return array(
                'code'=>206,
                'msg'=>'领取时间已过，该优惠券领取时间['.$coupon_data['collect_startdate'].'至'.$coupon_data['collect_enddate'].']');
        }
        $sql_chk = "SELECT count(id) FROM pft_member_coupon WHERE fid=? AND coupon_id=?";
        $query_param = array($mid, $coupon_id);
        if (!empty($from_ordernum)) {
            $sql_chk .= " AND from_ordernum=?";
            $query_param[] = $from_ordernum;
        }
        $stmt    = $this->db->prepare($sql_chk);
        $stmt->execute($query_param);
        $cnt_coupon = (int)$stmt->fetchColumn();
        if ( $coupon_data['collect_limit']>0 && $cnt_coupon >= $coupon_data['collect_limit']) {
            return array('code'=>205, 'msg'=>'您的优惠券已领完，谢谢参与');
        }
        $start_date = $coupon_data['use_startdate'];
        $end_date   = $coupon_data['use_enddate'];
        if ($coupon_data['effective_type']==0) {
            $start_date = $end_date = date('Y-m-d');
        }

        $array_collect = array(
            'fid'       => $mid,
            'aid'       => $aid,
            'coupon_id' => $coupon_id,
            'dstatus'   => 0,
            'start_date'=> $start_date,
            'end_date'  => $end_date,
            'create_time'=> date('Y-m-d H:i', $_SERVER['REQUEST_TIME']),
        );
        if (Db::Insert($array_collect, 'pft_member_coupon') > 0) {
            return array('code'=>200, 'msg'=>'领取成功',"coupon_name"=>$coupon_data['coupon_name']);
        }
        return array('code'=>0, 'msg'=>'领取失败');
    }

    public function auto_send(Array $app_id_list)
    {
        $sql = <<<SQL
SELECT c.id,c.pid,c.apply_did,c.coupon_name,t.id as tid FROM pft_coupons c
LEFT JOIN uu_jq_ticket t on t.pid=c.pid WHERE c.status=0
AND c.effective_type>1 AND c.pid>0
SQL;
        $stmt = $this->db->prepare($sql);
        $stmt->execute();
        $tid_list = $id_list = $id_apply= array();
        while($row=$stmt->fetch(\PDO::FETCH_ASSOC)) {
            $id_list[$row['id']]  = array(
                'pid'=>$row['pid'],
                'name'=>$row['coupon_name'],
                'aid'=>$row['apply_did'],
                'tid'=>$row['tid'],
            );
//            $id_apply[$row['id']] = $row['apply_did'];
        }
        $time = date('Y-m-d H:i:s', $_SERVER['REQUEST_TIME']);
        if (!count($id_list)) {
            file_put_contents('/var/www/html/new/d/logs/api/coupons/log.log',
                $time . ":没有自动发送的优惠券", FILE_APPEND);
            return true;
        }
//        $sql_get_pid = "SELECT id,pid FROM uu_jq_ticket WHERE pid IN("
//            .implode(',', $id_list).") LIMIT ".count($id_list);
//        $stmt = $this->db->prepare($sql_get_pid);
//        $stmt->execute();
//        while($row=$stmt->fetch(\PDO::FETCH_ASSOC)) {
//            $tid_list[$row['pid']] = $row['id'];
//        }
        $soap = new \SoapClient(null,array(
                "location" => "http://localhost/open/openService/pft_insideMX.php",
                "uri" => "www.16u.com?ac_16u=16ucom|pw_16u=c33367701511b4f6020ec61ded352059|auth_16u=true")
        );
        include '/var/www/html/wx/wechat/open_wechat.php';
//        print_r($id_list);
//        echo str_repeat("+", 100),PHP_EOL;
        foreach($id_list as $coupon_id=>$coupon) {
            if ($coupon['aid']==55) {
                define('DEFAULT_WECHAT_APPID', 'wx678d02326b6ba9d9');
                include '/var/www/html/wx/wechat/iwx.php';
                $access_token = null;
            } else {
                $appid = $app_id_list[$coupon['aid']];
                $access_token = \LaneWeChat\Core\OpenAccessToken::getAccessToken($appid);
            }
            $send_cnt_arr = $this->order_query_by_tid($coupon['tid'], $soap);
//            echo str_repeat("-", 100),PHP_EOL;
            if (!count($send_cnt_arr)) {
                file_put_contents('/var/www/html/new/d/logs/api/coupons/log.log',
                    $time . ":{$tid_list[$coupon['pid']]}没有订单", FILE_APPEND);
                continue;
            }
            file_put_contents('/var/www/html/new/d/logs/api/coupons/log.log',
                $time . ":发送优惠券:".json_encode($send_cnt_arr), FILE_APPEND);
            $mid_open_ids = array();
            $member_ids   = implode(',', array_keys($send_cnt_arr));
            $sql = "SELECT fid,fromusername FROM uu_wx_member_pft WHERE aid={$coupon['aid']} AND fid IN($member_ids)";
            $stmt = $this->db->prepare($sql);
            $stmt->execute();
            while($row=$stmt->fetch(\PDO::FETCH_ASSOC)) {
                $mid_open_ids[$row['fid']] = $row['fromusername'];
            }
//            print_r($send_cnt_arr);
            //exit;
            foreach($send_cnt_arr as $mid=>$cnt) {
//                self::setMid($mid);
                $ok_cnt = 0;
                for($i=0;$i<$cnt; $i++) {
                    $collect_ret = $this->collect_coupon($coupon_id,
                        $coupon['aid'], $mid);
                    if ($collect_ret['code']==200) {
                        $ok_cnt += 1;
                    }
                    file_put_contents('/var/www/html/new/d/logs/api/coupons/log.log',
                        $time . ":发送优惠券结果:".json_encode($collect_ret),
                        FILE_APPEND);
                }
                if (isset($mid_open_ids[$mid])) {
                    \LaneWeChat\Core\ResponseInitiative::text($mid_open_ids[$mid],
                        "恭喜您获得了{$ok_cnt}份{$coupon['name']}优惠券。"
                        ."点击<a href=\"http://100005.12301.cc/wx/html/"
                        ."sale_coupon.html\">优惠券列表</a>查看。感谢您的支持！",
                        $access_token);
                }

            }
        }
    }

    public function order_query_by_tid($tid, $soap)
    {
        $bt = date('Y-m-d 00:00:00', strtotime('-1 days'));//
        $et = date('Y-m-d 23:59:59', strtotime('-1 days'));//
//        echo $tid;
//        return;
        $xml = $soap->Order_Globle_Search(0, 0, 0, $tid, '', '', $bt, $et, '',
            '', '', '', '', '', '', '0|1', 1, '');
//        echo $xml;
        $order_list = simplexml_load_string($xml);
        $ret_list   = array();
        if (count($ret_list)==1) {
            return $ret_list[(int)$order_list->Rec->UUmid] =
                                                 (int)$order_list->Rec->UUtnum;
        }
        $tmp_arr = array();
        foreach($order_list as $row){
            if (in_array((int)$row->UUordernum, $tmp_arr)) continue;
            $tmp_arr[] = (int)$row->UUordernum;
            $ret_list[(int)$row->UUmid] += (int)$row->UUtnum;
        }
        return $ret_list;
    }
    /**
     * 每天定期执行 修改过期的优惠券状态
     *
     * @return int
     */
    public function over_date(){
        file_put_contents('/var/www/html/new/d/logs/coupons/over_date.txt','REQUEST FROM： ' . $_SERVER['REMOTE_ADDR']."\n",FILE_APPEND);
        $date  = date('Y-m-d 00:00:00', $_SERVER['REQUEST_TIME']);
        $this->over_date_member($date);
//        $sql_chk = "SELECT id FROM pft_coupons WHERE status<>2 and use_enddate<'$date'";
        $sql_chk = "SELECT id FROM pft_coupons WHERE status<>2 and collect_enddate<'$date'";
//        echo $sql_chk;
        $stmt  = $this->db->prepare($sql_chk);
        $stmt->execute();
        $coupon_ids = $stmt->fetchAll(\PDO::FETCH_COLUMN);
//        print_r($coupon_ids);
        if (!$coupon_ids) {
            return 0;
        }
        $sql_1 = "update pft_coupons set status=2 where id IN(".implode(',', $coupon_ids).")";
        $stmt  = $this->db->prepare($sql_1);
        $stmt->execute();
//        $sql_2 = "update pft_member_coupon set dstatus=1 where coupon_id IN(".implode(',', $coupon_ids).")";
//        echo $sql_2;
//        $stmt = $this->db->prepare($sql_2);
//        $stmt->execute();
        file_put_contents('/var/www/html/new/d/logs/coupons/over_date.txt',$date.'|'.$sql_1."\n",FILE_APPEND);
        return 200;
    }
    public function over_date_member($date)
    {
        $sql_chk_mem = "SELECT id FROM pft_member_coupon WHERE dstatus=0 AND end_date<'$date'";
        $stmt  = $this->db->prepare($sql_chk_mem);
        $stmt->execute();
        $mem_coupon_ids = $stmt->fetchAll(\PDO::FETCH_COLUMN);
        if (!$mem_coupon_ids) {
            return 0;
        }
        $sql_2 = "update pft_member_coupon set dstatus=1 where id IN(".implode(',', $mem_coupon_ids).")";
        $stmt = $this->db->prepare($sql_2);
        file_put_contents('/var/www/html/new/d/logs/coupons/over_date.txt',$date.'|'.$sql_2."\n",FILE_APPEND);
        $stmt->execute();
        return 200;
    }

    public function __destruct()
    {
        \PFT\Db::Close();
        $this->db = null;
        unset($this->db);
    }

}